package com.zhang.gulimall.order.web;

import com.alibaba.fastjson.JSON;
import com.zhang.gulimall.common.exception.NoStockException;
import com.zhang.gulimall.common.to.MemberTo;
import com.zhang.gulimall.order.service.OrderService;
import com.zhang.gulimall.order.vo.OrderConfirmVo;
import com.zhang.gulimall.order.vo.OrderSubmitVo;
import com.zhang.gulimall.order.vo.SubmitResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @RequestMapping("/{page}.html")
    public String confirm(@PathVariable String page) {
        return page;
    }

    @RequestMapping("/toTrade")
    public String toTrade(HttpSession session, Model model) {
        MemberTo member = JSON.parseObject(JSON.toJSONString(session.getAttribute("loginUser")), MemberTo.class);
        OrderConfirmVo items = orderService.confirmOrder(member.getId(), member);
        model.addAttribute("orderConfirmData", items);
        return "confirm";
    }

    @RequestMapping("/submitOrder")
    public String submitOrder(@RequestParam("token") String token, @RequestParam("addrId") String addrId, Model model) {
        OrderSubmitVo orderSubmitVo = new OrderSubmitVo();
        orderSubmitVo.setToken(token);
        orderSubmitVo.setAddrId(addrId);
        SubmitResponseVo resVo;
        try {
            resVo = orderService.submitOrder(orderSubmitVo);
        } catch (NoStockException e){
            return "redirect:http://localhost:11000/toTrade";
        }
        model.addAttribute("submitResponseVo",resVo);
        if (resVo.getCode() == 0) {
            return "pay";
        } else {
            return "redirect:http://localhost:11000/toTrade";
        }
    }
}
